package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exception.guliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * zz: wzh
 * time 2022 09 21 21 31
 **/
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    //这个类无法被spring管理,需要自己new,也不能注入其他对象
    //无法实现数据库炒作
    public EduSubjectService eduSubjectService;

    public SubjectExcelListener() {
    }
    public SubjectExcelListener(EduSubjectService eduSubjectService){
        this.eduSubjectService=eduSubjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData==null){
            throw new guliException(20001,"文件数据为空");
        }
        EduSubject eduSubject = this.existOneSubject(eduSubjectService, subjectData.getOneObjectName());
        if (eduSubject==null){
            eduSubject=new EduSubject();
            eduSubject.setParentId("0");
            eduSubject.setTitle(subjectData.getOneObjectName());
            eduSubjectService.save(eduSubject);
        }
        String pid=eduSubject.getId();
        EduSubject subject = this.existTwoSubject(eduSubjectService, subjectData.getTwoObjectName(), pid);
        if (subject==null){
            subject=new EduSubject();
            subject.setParentId(pid);
            subject.setTitle(subjectData.getTwoObjectName());
            eduSubjectService.save(subject);
        }

    }
    //判断一级分类不能重复添加
    private EduSubject existOneSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",0);
        EduSubject one = eduSubjectService.getOne(wrapper);
        return one;
    }
    //判断二级分类不能重复添加
    private EduSubject existTwoSubject(EduSubjectService eduSubjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject one = eduSubjectService.getOne(wrapper);
        return one;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
